var basicWordList = require('../../../data/word-list-zk.js')
var intermediateWordList = require('../../../data/word-list-gk.js');
var advancedWordList = require('../../../data/word-list-cet6.js');

Page({

    data: {
      unknownWords: [], // 存储用户不认识的词
      showNot: false,
      content: '',
      pron: '',
      definition: '',
      audio: '',
      wordCounter: 0 ,// 单词计数器
      currentWord: {}, //当前显示的单词对象
      favoriteWords: [], // 存储收藏的单词
      isFavorited: false, // 是否已收藏
      learnedWords: [], // 存储已学习的单词索引
      wordList: [] // 当前词汇列表
    },

    onLoad: function (options) {

      // 加载收藏的词汇
      const favoriteWords = wx.getStorageSync('favoriteWords') || [];
      this.setData({ favoriteWords });
      this.checkIfFavorited(); // 检查当前单词是否已收藏
      // 加载用户唯一标识符
      const uniqueId = wx.getStorageSync('uniqueId');
      this.setData({
        uniqueId: uniqueId
      });

      // 获取用户选择的词库
      let selectedWordList = wx.getStorageSync('selectedWordList');
      // 根据选择的词库加载不同的词汇表
      let wordList = [];
      if (selectedWordList === '基础词汇') {
          wordList = basicWordList.wordList;
      } else if (selectedWordList === '中级词汇') {
          wordList = intermediateWordList.wordList;
      } else if (selectedWordList === '高级词汇') {
          wordList = advancedWordList.wordList;
      }
      // 获取用户的学习进度
      let progressKey = `learningProgress_${uniqueId}`;
      let learningProgress = wx.getStorageSync(progressKey) || {
          learnedWords: [],
          learnedCount: 0
      };
      this.setData({
          wordList: wordList,
          learnedWords: learningProgress.learnedWords
      });
      this.showWord(); // 加载单词
    },

    // 检查当前单词是否已收藏
    checkIfFavorited: function() {
      const { currentWord, favoriteWords } = this.data;
      const isFavorited = favoriteWords.some(word => word.content === currentWord.content);
      this.setData({ isFavorited });
    },

    // 切换收藏状态
    toggleFavorite: function() {
      const { currentWord, favoriteWords, isFavorited } = this.data;

      if (isFavorited) {
        // 如果已收藏，取消收藏
        const updatedFavorites = favoriteWords.filter(word => word.content !== currentWord.content);
        this.setData({ 
          favoriteWords: updatedFavorites, 
          isFavorited: false 
        });
        wx.setStorageSync('favoriteWords', updatedFavorites); // 更新本地存储
        wx.showToast({ title: '已取消收藏', icon: 'none' });
      } else {
        // 如果未收藏，添加收藏
        favoriteWords.push(currentWord);
        this.setData({ 
          favoriteWords, 
          isFavorited: true 
        });
        wx.setStorageSync('favoriteWords', favoriteWords); // 更新本地存储
        wx.showToast({ title: '已收藏', icon: 'success' });
      }
    },

    showWord: function() {
      // 获取未学习的单词
      let availableWords = this.data.wordList.filter((_, idx) => !this.data.learnedWords.includes(idx));
      // 如果所有单词都学完了，重置 learnedWords 或提示用户
      if (availableWords.length === 0) {
          wx.showToast({
              title: '所有单词都学习过一次了！',
              icon: 'none',
              duration: 2000
          });
          this.setData({
              learnedWords: [] // 重置已学习的单词索引
          });
          availableWords = this.data.wordList; // 重置可用的单词
      }

      // 从词表中随机取一个词
      var idx = Math.floor(Math.random() * availableWords.length);
      var word = availableWords[idx];
      
      // 更新当前显示的词数据
      this.setData({
          currentWord: word, // 保存当前展示的单词对象
          content: word.content,
          pron: word.pron,
          definition: word.definition,
          audio: word.audio,
          showNot: false, // 隐藏“不认识”标记
          isFavorited: false // 每次加载新单词时默认未收藏
      });
      // 检查新单词是否已收藏并更新收藏状态
      this.checkIfFavorited();
    },

    show: function () {
        this.setData({
            showNot: true
        });
        // 将不认识的词存入unknownWords数组
        let unknownWord = {
          content: this.data.content,
          pron: this.data.pron,
          definition: this.data.definition,
          audio: this.data.audio
        };

        // 更新 unknownWords 数组
        let updatedUnknownWords = this.data.unknownWords;
        updatedUnknownWords.push(unknownWord);
        this.setData({
            unknownWords: updatedUnknownWords
        });

         // 如果 unknownWords 数组达到 5 个，跳转到复习页面
         if (updatedUnknownWords.length >= 5) {
            wx.setStorageSync('unknownWords', updatedUnknownWords); // 保存数据供复习页面使用
            this.setData({
                unknownWords: [] // 清空当前数组
            });
            wx.navigateTo({
                url: '/packageE/pages/reword/reword' // 跳转到复习页面
            });
          }
    },

    next: function () {
      // 只有点击“下一单词”时，才将当前单词加入 learnedWords
      let learnedIdx = this.data.wordList.findIndex(w => w.content === this.data.currentWord.content);
      if (!this.data.learnedWords.includes(learnedIdx)) {
        this.data.learnedWords.push(learnedIdx);
      }
      // 增加单词计数器
      this.setData({
        wordCounter: this.data.wordCounter + 1,
        learnedWords: this.data.learnedWords // 更新 learnedWords 数据到页面中
      });
      // 更新学习进度到本地存储
      this.updateLearningProgress();
      this.showWord(); // 显示下一个随机单词
    },

    read: function () {
        console.log(this.data.audio)
        wx.playVoice({
            filePath: this.data.audio,
            success: function (res) {
                console.log('ok')
            },
            fail: function () {
                console.log('fail');
            },
            complete: function () {
                console.log('complete');
            }
        })
    },

    // 更新学习进度到本地存储
    updateLearningProgress: function () {
      const uniqueId = this.data.uniqueId;
      const progressKey = `learningProgress_${uniqueId}`;
      const learningProgress = {
        learnedWords: this.data.learnedWords,
        learnedCount: this.data.learnedWords.length 
      };

      wx.setStorageSync(progressKey, learningProgress);
    }

})